package com.longe.nio.buffer;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * MappedByteBuffer可以让文件直接在内存(堆外的内存)中进行修改
 * 而如何同步到文件由NIO来完成
 * 其子类有：DirectByteBuffer和DirectByteBufferR
 */
public class MappedByteBufferTest {

    public static void main(String[] args) throws Exception {

        RandomAccessFile randomAccessFile = new RandomAccessFile("demo1.txt", "rw");
        //获取对应的通道
        FileChannel channel = randomAccessFile.getChannel();

        //获取MappedByteBuffer
        //第一个参数设置为读写,第二个参数表示从哪个位置开始, 第三个参数表示映射到内存的大小
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);

        mappedByteBuffer.put(0, (byte)'H');
        mappedByteBuffer.put(4, (byte)'O');

        randomAccessFile.close();
    }
}
